let Table = function (options) {
	let self = $.extend(this, options);
	/*常量*/
	self.CONSTANT = {
		DATA_TABLES: {
			DEFAULT_OPTION: { //DataTables初始化选项

			},
			COLUMN: {
				CHECKBOX: { //复选框单元格
					className: "td-checkbox",
					orderable: false,
					width: "30px",
					data: null,
					render: function (data, type, row, meta) {
						return '<input type="checkbox" class="icheckbox-primary hide" data-checkbox-class="icheckbox_flat-blue" data-plugin="iCheck">';
					}
				},
				MONEY: {

				}
			},
			RENDER: { //常用render可以抽取出来，如日期时间、头像等
				ELLIPSIS: function (data, type, row, meta) {
					data = data || "";
					return '<span title="' + data + '">' + data + '</span>';
				},
				DATE: function (data, type, row, meta) {
					if (data) {
						return new Date(data).Format("yyyy-MM-dd hh:mm:ss");
					} else {
						return "";
					}

				},
				MONEY: function (data, type, row, meta) {
					return fcUtil.math.decimal(data);
				}
			}
		}
	};
	self.DEFAULT = {
		"responsive": true,
		"bDeferLoading": true,
		"serverSide": true,
		"bProcessing": true,
		"ajax": "load",
		"bLengthChange": true, // 开关，是否显示每页大小的下拉框
		"iDisplayLength": 50, // 每页显示20条数据
		"bInfo": true, // 开关，是否显示表格的一些信息
		"bFilter": true, // 开关，是否启用客户端过滤器
		"bAutoWidth": false, // 自适应宽度
		"bDeferRender": false,
		"bPaginate": true, // 开关，是否显示（使用）分页器
		"sScrollX": true, //是否开启水平滚动，以及指定滚动区域大小,可设值：'disabled','2000%' //
		"bScrollInfinite": false, // 开关，以指定是否无限滚动（与
		"scrollY": 400,
		"scrollX": true,
		"bSort": true, // 开关，是否启用各列具有按列排序的功能 //
		"bSortClasses": true, // 开关，指定当当前列在排序时，是否增加 classes 'sorting_1',
		"bScrollCollapse": false, // 当设置sScrolly时 如果数据没那么高 表格是否自适应高度
		"bJQueryUI": false, // 开关，是否启用JQueryUI风格 导致导航框一直出不来
		"bStateSave": false, // 开关，是否打开客户端状态记录功能。这个数据是记录在cookies中的，打开了这个记录后，即使刷新一次页面，或重新打开浏览器，之前的状态都是保存下来的-
		"dom": "r<'data_table't>" + "<'main_table_info'<'col-sm-5'i><'col-sm-7'p>>",
		"sPaginationType": "full_numbers", // 显示数字的翻页样式
		"language": {
			"sSearchPlaceholder": "快速查找",
			"lengthMenu": "每页显示 _MENU_ 条",
			"search": "_INPUT_",
			"info": "第 _START_ 至 _END_ 项，共 _TOTAL_ 项",
			"infoEmpty": "共 0 项",
			"emptyTable": "无数据",
			"zeroRecords": "抱歉，没有找到符合条件的记录",
			"sInfoFiltered": "(从 _MAX_ 条记录中查找)",
			"loadingRecords": "加载中，请稍后…",
			"processing": "",
			"paginate": {
				"first": "第一页",
				"last": "最后一页",
				"previous": '<i  class="icon wb-chevron-left-mini"></i>',
				"next": '<i   class="icon wb-chevron-right-mini"></i>'
			},
			"aria": {
				"sortAscending": "升序排列",
				"sortDescending": "降序排列"
			}
		}
	};

	self.getQueryCondition = function (data) {
		let param = {};
		//组装排序参数
		if (data.order && data.order.length && data.order[0]) {
			//排序 字段
			param.orderColumn = data.columns[data.order[0].column].data;
			//升序|降序
			param.orderDir = data.order[0].dir;
		}
		//组装查询参数
		if (self.search_btn && $(self.search_btn).length) {
			let $form = $(self.search_btn).parents('form:eq(0)');
			param = $.extend(fcUtil.formToJson($form), param);
		}
		//组装分页参数
		param.startIndex = data.start || 0;
		param.pageSize = data.length || 20;
		param.pageIndex = data.start ? data.start / 50 : 0;
		param.draw = data.draw || 1;
		return param;
	};
	//--------------------------------------------
	self.init = function () {
		self.tableContainer = $(self.element).parent();
		self.tableContainer.addClass('table-loading');
		let $table = $(self.element);
		if (!$table.hasClass('dataTable')) {
			self.init_table();
		}
		self.iCheck();


		if (self.search_btn && $(self.search_btn).length) {
			let $form = $(self.search_btn).parents('form:eq(0)');
			$form.append('<input type="text" class="hide"/>');
			$form.submit(function (e) {
				self.api.draw();
				return false;
			}).keyup(function (e) {
				if (event.keyCode == 13) {
					$(this).submit();
				}
			})
		}
	}
	self.init_table = function (view) {
		self.$table = $(self.element);
		self.columns = [];
		//处理checkbox
		if (self.$table.find('th[data-type="checkbox"]').length) {
			self.$table.find('th[data-type="checkbox"]').html(self.CONSTANT.DATA_TABLES.COLUMN.CHECKBOX.render());
		}
		//---
		self.$table.find('th').each(function (th) {
			//checkbox
			if ($(this).data('type') == 'checkbox') {
				self.columns.push(self.CONSTANT.DATA_TABLES.COLUMN.CHECKBOX);
			} else {
				let data = {
					data: $(this).data('field') || null,
					orderable: $(this).data('orderable') || false,
					defaultContent: ''
				}
				if ($(this).data('render')) {
					let key = $(this).data('render');
					if (key.indexOf('.') == -1) {
						//判断是否有内置rander
						if (self.CONSTANT.DATA_TABLES.RENDER[key.toUpperCase()]) {
							data.render = self.CONSTANT.DATA_TABLES.RENDER[key.toUpperCase()];
						} else {
							data.render = window[$(this).data('render')];
						}

					} else {
						let keys = key.split('.');
						let render = null;
						for (let i = 0; i < keys.length; i++) {
							if (render) {
								render = render[keys[i]];
							} else {
								render = window[keys[i]];
							}

						}
						data.render = render;
					}

				}
				if ($(this).data('className')) {
					data.className = $(this).data('className');
				}
				if ($(this).data('cssclass')) {
					data.className = $(this).data('cssclass');
				}
				self.columns.push(data);
			}

		})

		self.DEFAULT.sScrollY = ($('.wd-table-container').height() - 52 - 43);

		self.tableOptions = $.extend(self.DEFAULT, options, {
			ajax: function (data, callback, settings) {
				//ajax配置为function,手动调用异步查询
				//封装请求参数
				let params = self.getQueryCondition(data);
				for (let key in params) {
					if (params[key] == '' || params[key] == null) {
						delete (params[key])
					}
				};
				wdAjax({
					type: "GET",
					url: self.url,
					cache: false, //禁用缓存
					data: params, //传入已封装的参数
					dataType: "json",
					success: function (result) {
						//封装返回数据，这里仅演示了修改属性名
						let returnData = {
							sEcho: params.draw, //页面发来的参数，原样返回
							iTotalRecords: result.totalCount || result.total || 0, //过滤前总记录数, 
							iTotalDisplayRecords: result.totalCount || result.total || 0, // 过滤后总记录数，我没有使用过滤，不太清楚和iTotalRecords的区别, 
							aaData: result.dataList || result.pageData || [] //, //包含数据的2维数组 
							//iDisplayStart: 0, // 起始 
							//iDisplayLength: 10 // size
						};
						callback(returnData);

						//获取合计数据
						if (self.total_url) {
							wdAjax({
								type: "GET",
								url: self.total_url,
								cache: false, //禁用缓存
								data: params, //传入已封装的参数
								dataType: "json",
								success: function (result) {
									$('.dataTables_scrollFootInner td[data-field]').each(function (i, td) {
										let field = $(td).data('field');
										$(td).text(fcUtil.math.decimal(result[field]) || '0.00');
									})
								}
							})
						}
						self.updataColumnWidth.call(self);
					}
				});
			},
			"columns": self.columns,
			"createdRow": function (row, data, index) {
			},
			"initComplete": function (settings) {
				log('-------initComplete------');
				fcUtil.setIcon();
				this.data('datatables', this);
				this.data('settings', settings);
				this.data('reload', this.api().ajax.reload);
				this.fnAdjustColumnSizing(false);
				//self.updataColumnWidth.apply(this);
				$(settings.nScrollBody).addClass('s-height');
				setTimeout(function () {
					fcUtil.sHeight($(settings.nScrollBody).parent());
					//初始化滚动条
					let nicescroll = $(settings.nScrollBody).niceScroll($.po('niceScroll'));
					$(settings.nScrollBody).attr('data-plugin', 'niceScroll');
				}, 100)

				self.tableContainer.removeClass('table-loading');
			},
			"drawCallback": function (settings) {
				log('-------drawCallback-----');
				fcUtil.updataAuthority();
				fcUtil.setIcon();
				$.components.init(undefined, undefined, $('#wd-pageContent'));

				if (settings.aoData.length == 0) {
					$('.dataTables_paginate.paging_full_numbers').hide();
				} else {
					$('.dataTables_paginate.paging_full_numbers').show();
				}
				if (options.callback) {
					options.callback.apply(self);
				}
				fcUtil.sHeight();
			}
		});

		self.afterSetTableOptions(function () {
			console.log('----setOptions----')
			self._table = self.$table.dataTable(self.tableOptions);
			self.api = self._table.api();
			//---------------------------------------绑定事件
			//搜索按钮
			if (self.search_btn && $(self.search_btn).length) {
				$(self.search_btn).unbind('click.datatables').bind('click.datatables', function () {
					let flag = true;
					if (self.before_table_data) {
						self.before_table_data.call(self)
					}
					if (flag) {
						self.api.draw();
						$(".dataTables_wrapper").find('th[data-type="checkbox"]').iCheck('uncheck');
					}
				})
			}

			if (self.view.container.find('#reset-btn').length) {
				self.view.container.find('#reset-btn').unbind('click.fctable').bind('click.fctable', function () {
					$('.group-bootstrap-select select:not(:first)').each(function (i, select) {
						$(select).find('option[value!=""]').remove();
						$(select).data('selectpicker').destroy()
						$(select).selectpicker($.po('selectpicker', {
							noneSelectedText: '请选项'
						}));
					});
					$(this).parents('form:eq(0)')[0].reset();
					let selectArr = $(this).parents('form:eq(0)').find('[data-plugin="selectpicker"]');
					for (let i = 0; i < selectArr.length; i++) {
						$(selectArr[i]).data('selectpicker').refresh();
					}
				})
			}
		});



	}

	self.afterSetTableOptions = function (callback) {
		callback();
	}
	self.updataColumnWidth = function () {
		let tableContainer = $(this.element).parents('.data_table:eq(0)');
		if (self.tableOptions.fixedColumns) {
			tableContainer = $(this.element).parents('.DTFC_ScrollWrapper:eq(0)');
		}
		if (tableContainer.find('.dataTables_scrollBody').width() > tableContainer.find('.dataTables_scrollBody>table').width() && tableContainer.find('.dataTables_empty').length == 0 && (tableContainer.find('.dataTables_scrollHeadInner').width() + 17) != tableContainer.find('.dataTables_scrollHeadInner>table').width()) {
			let width = tableContainer.find('.dataTables_scrollHeadInner').width() + 17;
			tableContainer.find('table').width(width)
		}
		return false;

	}
	self.iCheck = function () {
		this.view.container.on('ifClicked', 'th[data-type="checkbox"] input[type=checkbox]', function () {
			//选中 th里面的checkbox
			setTimeout(function () {
				let checkbox = $(self.element).find('td input[type=checkbox]');

				if ($(this).prop('checked')) {
					// 	$(self.element).find('td input[type=checkbox]').iCheck('check');
					checkbox.each(function () {
						if (!$(this).prop('disabled')) {
							$(this).iCheck('check');
						}
					})
				} else {
					// $(self.element).find('td input[type=checkbox]').iCheck('uncheck');
					checkbox.each(function () {
						if (!$(this).prop('disabled')) {
							$(this).iCheck('uncheck');
						}
					})
				}
			}.bind(this))
		});
		this.view.container.on('ifClicked', 'td input[type=checkbox]', function () {
			//选中 td里面的checkbox
			setTimeout(function () {
				if ($(this).parents('table').find('tbody tr').length == $(this).parents('table').find('tbody tr input[type=checkbox]:checkbox:checked').length) {
					self.view.container.find('th[data-type="checkbox"] input[type=checkbox]').iCheck('check');
				} else {
					self.view.container.find('th[data-type="checkbox"] input[type=checkbox]').iCheck('uncheck');
				}
			}.bind(this))
		});
	}
	return self;
};

